<template>
  <el-container class="flow-info-container">
    <el-main>
      <div style="position: relative;">
        <el-form ref="formFlowEntry" :model="formFlowEntry" label-width="100px" size="mini" label-position="right" @submit.native.prevent>
          <FilterBox :item-width="300">
            <el-form-item label="流程分类" prop="formFilter.categoryId">
              <el-select
                v-model="formFlowEntry.formFilter.categoryId"
                class="filter-item"
                :clearable="true"
                filterable
                placeholder="流程分类"
                :loading="formFlowEntry.categoryIdWidget.loading"
                @visible-change="formFlowEntry.categoryIdWidget.onVisibleChange"
              >
                <el-option v-for="item in formFlowEntry.categoryIdWidget.dropdownList" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="流程名称" prop="formFilter.processDefinitionName">
              <el-input v-model="formFlowEntry.formFilter.processDefinitionName" class="filter-item" :clearable="true" placeholder="流程名称" />
            </el-form-item>
            <el-form-item label="流程标识" prop="formFilter.processDefinitionKey">
              <el-input v-model="formFlowEntry.formFilter.processDefinitionKey" class="filter-item" :clearable="true" placeholder="流程标识" />
            </el-form-item>
            <el-form-item label="发布状态" prop="formFilter.status">
              <el-select v-model="formFlowEntry.formFilter.status" class="filter-item" :clearable="true" filterable placeholder="发布状态">
                <el-option v-for="item in SysFlowEntryPublishedStatus.getList()" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
            <el-button slot="operator" type="default" :plain="true" size="mini" @click="onReset">重置</el-button>
            <el-button slot="operator" type="primary" :plain="true" size="mini" @click="refreshFormFlowEntry(true)">查询</el-button>
          </FilterBox>
        </el-form>
        <el-card shadow="never" class="tableCard">
          <el-row>
            <el-col :span="24">
              <vxe-toolbar :refresh="{query: refresh}">
                <template v-slot:buttons>
                  <el-button type="primary" icon="el-icon-plus" size="small" @click="onAddFlowBasicClick()">新建</el-button>
                </template>
              </vxe-toolbar>
              <el-table
                ref="flowEntry"
                border
                max-height="420"
                :header-cell-style="{background:'#f4f4f4', color:'#717171' }"
                :data="formFlowEntry.flowEntryWidget.dataList"
                size="middle"
                header-cell-class-name="table-header-gray"
                @sort-change="formFlowEntry.flowEntryWidget.onSortChange"
              >
                <el-table-column label="序号" header-align="center" align="center" type="index" width="55px" :index="formFlowEntry.flowEntryWidget.getTableIndex" />
                <el-table-column label="缩略图" prop="thumbIcon" align="center" width="70px">
                  <template slot-scope="scope">
                    <el-avatar class="avatar-info" shape="square" size="small" fit="cover" :icon="scope.row.thumbIcon" />
                  </template>
                </el-table-column>
                <el-table-column label="流程名称" prop="processDefinitionName" width="180px" />
                <el-table-column label="流程标识" prop="processDefinitionKey" width="150px" />
                <el-table-column label="流程分类" prop="flowCategory.name" width="150px" />
                <el-table-column label="发布状态" prop="status" width="100px">
                  <template slot-scope="scope">
                    <el-tag size="small" :type="scope.row.status === SysFlowEntryPublishedStatus.PUBLISHED ? 'success' : 'warning'">
                      {{ SysFlowEntryPublishedStatus.getValue(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="流程主版本" prop="mainFlowEntryPublish" header-align="center" align="center" width="150px">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.mainFlowEntryPublish" size="small" type="primary" effect="dark">
                      {{ 'V:' + scope.row.mainFlowEntryPublish.publishVersion }}
                    </el-tag>
                    <el-tag v-if="scope.row.mainFlowEntryPublish" size="small" effect="dark" style="margin-left: 10px" :type="scope.row.mainFlowEntryPublish.activeStatus ? 'success' : 'danger'">
                      {{ scope.row.mainFlowEntryPublish.activeStatus ? '激活' : '挂起' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="最近发布时间" prop="latestPublishTime" sortable="custom" width="180px" />
                <el-table-column label="创建时间" prop="createTime" sortable="custom" width="180px" />
                <el-table-column label="操作" fixed="right" width="180px">
                  <template slot-scope="scope">
                    <el-button class="table-btn success" type="text" size="small" :disabled="!(scope.row.mainFlowEntryPublish && scope.row.mainFlowEntryPublish.activeStatus)" @click.stop="onStartFlowEntryClick(scope.row)">启动</el-button>
                    <el-button class="table-btn success" type="text" size="small" @click.stop="onEditFlowBasicClick(scope.row)">编辑</el-button>
                    <el-button class="table-btn success" type="text" size="small" @click.stop="onEditFlowVariableClick(scope.row)">变量</el-button>
                    <el-button class="table-btn success" type="text" size="small" @click.stop="onEditFlowEntryClick(scope.row)">设计</el-button>
                    <el-button type="text" size="small" @click.stop="onPublishedClick(scope.row)">发布</el-button>
                    <el-button type="text" size="small" @click.stop="onPublishedEntryListClick(scope.row)">版本</el-button>
                    <el-button class="table-btn delete" type="text" size="small" @click.stop="onDeleteFlowEntryClick(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-row type="flex" justify="end" style="margin-top: 10px;">
                <el-pagination
                  :total="formFlowEntry.flowEntryWidget.totalCount"
                  :current-page="formFlowEntry.flowEntryWidget.currentPage"
                  :page-size="formFlowEntry.flowEntryWidget.pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, prev, pager, next, sizes"
                  @current-change="formFlowEntry.flowEntryWidget.onCurrentPageChange"
                  @size-change="formFlowEntry.flowEntryWidget.onPageSizeChange"
                />
              </el-row>
            </el-col>
          </el-row>
        </el-card>
        <!--
        <FormEditFlowEntry v-if="showFlowEntryDesign" :flow-entry="currentFlowEntry" @close="onEditFlowEntryClose" />
        -->
      </div>
    </el-main>
  </el-container>
</template>

<script>
import '@/staticDict/flowStaticDict.js'
/* eslint-disable-next-line */
import { DropdownWidget, TableWidget } from '@/utils/widget.js'
/* eslint-disable-next-line */
import { uploadMixin, statsDateRangeMixin, cachePageMixin } from '@/core/mixins'
/* eslint-disable-next-line */
import { FlowEntryController, FlowDictionaryController, FlowOperationController } from '@/api/flowController.js'
import FormEditFlowBasic from './formEditFlowBasic.vue'
import FormFlowEntryVariable from './formFlowEntryVariable.vue'
import FormPublishedFlowEntry from './formPublishedFlowEntry.vue'
import FormEditFlowEntry from './formEditFlowEntry.vue'
import FilterBox from '@/components/FilterBox'
import '@/components/Dialog'

export default {
  name: 'FormFlowEntry',
  components: {
    // FormEditFlowEntry,
    FilterBox
  },
  mixins: [uploadMixin, statsDateRangeMixin, cachePageMixin],
  props: {
  },
  data() {
    return {
      showFlowEntryDesign: false,
      currentFlowEntry: undefined,
      formFlowEntry: {
        formFilter: {
          status: undefined,
          categoryId: undefined,
          processDefinitionName: undefined,
          processDefinitionKey: undefined
        },
        formFilterCopy: {
          status: undefined,
          categoryId: undefined,
          processDefinitionName: undefined,
          processDefinitionKey: undefined
        },
        categoryIdWidget: new DropdownWidget(this.loadCategoryIdDropdownList),
        flowEntryWidget: new TableWidget(this.loadFlowEntryWidgetData, this.loadFlowEntryVerify, true, false, 'entryId', 1),
        isInit: false
      }
    }
  },
  watch: {
  },
  mounted() {
    // 初始化页面数据
    this.formInit()
  },
  methods: {
    onReset() {
      this.$refs.formFlowEntry.resetFields()
      this.refreshFormFlowEntry(true)
    },
    onEditFlowEntryClose() {
      this.showFlowEntryDesign = false
      this.currentFlowEntry = null
      this.refreshFormFlowEntry()
    },
    /**
     * FlowEntry数据获取函数，返回Promise
     */
    loadFlowEntryWidgetData(params) {
      if (params == null) params = {}
      params = {
        ...params,
        flowEntryDtoFilter: {
          categoryId: this.formFlowEntry.formFilterCopy.categoryId,
          processDefinitionName: this.formFlowEntry.formFilterCopy.processDefinitionName,
          processDefinitionKey: this.formFlowEntry.formFilterCopy.processDefinitionKey,
          status: this.formFlowEntry.formFilterCopy.status
        }
      }
      return new Promise((resolve, reject) => {
        FlowEntryController.list(params).then(res => {
          resolve({
            dataList: res.data.dataList,
            totalCount: res.data.totalCount
          })
        }).catch(e => {
          reject(e)
        })
      })
    },
    /**
     * FlowEntry数据获取检测函数，返回true正常获取数据，返回false停止获取数据
     */
    loadFlowEntryVerify() {
      this.formFlowEntry.formFilterCopy.categoryId = this.formFlowEntry.formFilter.categoryId
      this.formFlowEntry.formFilterCopy.processDefinitionName = this.formFlowEntry.formFilter.processDefinitionName
      this.formFlowEntry.formFilterCopy.processDefinitionKey = this.formFlowEntry.formFilter.processDefinitionKey
      this.formFlowEntry.formFilterCopy.status = this.formFlowEntry.formFilter.status
      return true
    },
    /**
     * 流程分类下拉数据获取函数
     */
    loadCategoryIdDropdownList() {
      return new Promise((resolve, reject) => {
        const params = {}
        FlowDictionaryController.dictFlowCategory(params).then(res => {
          resolve(res.getList())
        }).catch(e => {
          reject(e)
        })
      })
    },
    /**
     * 流程分类选中值改变
     */
    onCategoryIdValueChange(value) {
    },
    /**
     * 更新流程设计
     */
    refreshFormFlowEntry(reloadData = false) {
      if (reloadData) {
        this.formFlowEntry.flowEntryWidget.refreshTable(true, 1)
      } else {
        this.formFlowEntry.flowEntryWidget.refreshTable()
      }
      if (!this.formFlowEntry.isInit) {
        // 初始化下拉数据
      }
      this.formFlowEntry.isInit = true
    },
    /**
     * 启动
     */
    onStartFlowEntryClick(row) {
      const params = {
        processDefinitionKey: row.processDefinitionKey
      }
      FlowOperationController.viewInitialTaskInfo(params).then(res => {
        if (res.data && res.data.taskType === this.SysFlowTaskType.USER_TASK && res.data.assignedMe) {
          this.$router.push({
            name: res.data.routerName || 'handlerFlowTask',
            query: {
              processDefinitionKey: row.processDefinitionKey,
              formId: res.data.formId,
              routerName: res.data.routerName,
              readOnly: res.data.readOnly,
              taskName: '启动流程',
              flowEntryName: row.processDefinitionName,
              operationList: (res.data.operationList || []).filter(item => {
                return item.type !== this.SysFlowTaskOperationType.CO_SIGN && item.type !== this.SysFlowTaskOperationType.REVOKE
              }),
              variableList: res.data.variableList
            }
          })
        } else {
          FlowOperationController.startOnly({
            processDefinitionKey: row.processDefinitionKey
          }).then(res => {
            this.$message.success('启动成功！')
          }).catch(e => {})
        }
      }).catch(e => {})
    },
    /**
     * 新建
     */
    onAddFlowBasicClick() {
      const params = {}

      this.$dialog.show('新建', FormEditFlowBasic, {
        area: '500px'
      }, params).then(res => {
        this.refreshFormFlowEntry()
      }).catch(e => {})
    },
    /**
     * 编辑基本信息
     */
    onEditFlowBasicClick(row) {
      this.currentFlowEntry = row
      const params = {
        flowEntry: row
      }

      this.$dialog.show('新建', FormEditFlowBasic, {
        area: '500px'
      }, params).then(res => {
        this.formFlowEntry.flowEntryWidget.refreshTable()
      }).catch(e => {})
    },
    /**
     * 编辑
     */
    onEditFlowEntryClick(row) {
      this.currentFlowEntry = row
      // this.showFlowEntryDesign = true
      const params = {
        flowEntry: row
      }

      this.$dialog.show('流程设计', FormEditFlowEntry, {
        area: ['1200px', '650px']
      }, params).catch(e => {})
    },
    onEditFlowVariableClick(row) {
      this.currentFlowEntry = row
      this.$dialog.show('变量管理', FormFlowEntryVariable, {
        area: '650px'
      }, {
        flowEntry: row
      }).catch(e => {})
    },
    /**
     * 发布
     */
    onPublishedClick(row) {
      this.$confirm('是否发布当前工作流设计？').then(res => {
        if (
          row.entryId == null
        ) {
          this.$message.error('请求失败，发现必填参数为空！')
          return
        }
        const params = {
          entryId: row.entryId
        }

        FlowEntryController.publish(params).then(res => {
          this.$message.success('发布成功')
          this.refreshFormFlowEntry()
        }).catch(e => {})
      }).catch(e => {})
    },
    /**
     * 版本管理
     */
    onPublishedEntryListClick(row) {
      this.$dialog.show('版本管理', FormPublishedFlowEntry, {
        area: ['1000px', '550px']
      }, {
        flowEntry: row
      }).then(res => {
        this.refreshFormFlowEntry()
      }).catch(e => {
        this.refreshFormFlowEntry()
      })
    },
    /**
     * 删除
     */
    onDeleteFlowEntryClick(row) {
      if (
        row.entryId == null
      ) {
        this.$message.error('请求失败，发现必填参数为空！')
        return
      }
      const params = {
        entryId: row.entryId
      }

      this.$confirm('是否删除此流程？').then(res => {
        FlowEntryController.delete(params).then(res => {
          this.$message.success('删除成功')
          this.formFlowEntry.flowEntryWidget.refreshTable()
        }).catch(e => {})
      }).catch(e => {})
    },
    refresh() {
      this.refreshFormFlowEntry(true)
    },
    onResume() {
      this.refreshFormFlowEntry()
    },
    initFormData() {
    },
    formInit() {
      this.refreshFormFlowEntry()
    }
  }
}
</script>

<style lang="scss">
  .flow-info-container {
    display: flex;

    flex-direction: column;
    margin: 0 auto;
    .blueLink {
      color: #409eff;
      font-size: 14px;
      margin-left: 20px;
      cursor: pointer;
    }
    .btnList {
      margin-top:20px;
      display: flex;
      justify-content: right;
      float: right;
      .submitBtn {
        margin-right: 30px;
      }
    }
    .fromFlex {
      height: 36px;
      display: flex;
      align-items: center;
    }
    .base-info {
      display: flex;
      margin-bottom: 20px;
      .basics-info {
        width: 100%;
      }
    }
    .avatar-info {
      width: 40px;
      height: 40px;
      line-height: 40px;
      background: #409eff;
    }
  }
</style>
